package com.dbapp.imglib.imageloader;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.File;

/**
 * Created by Arirus on 2017/8/2.
 */

public class SelectLocalPicActivity extends AppCompatActivity {

  private static final int REQUEST_ALBUM = 110;
  private static OnPicPickListener sListener;
  private Uri mUri;

  public static void start(Context context ,OnPicPickListener listener) {
    sListener = listener;
    Intent starter = new Intent(context, SelectLocalPicActivity.class);
    context.startActivity(starter);
  }

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
    startActivityForResult(photoPickerIntent, REQUEST_ALBUM);
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_ALBUM&& resultCode == RESULT_OK){
      Uri newUri;
      newUri = data.getData();
      String path = null;
      Cursor cursor = getContentResolver().query(newUri, null, null, null, null);
      if (cursor != null) {
        if (cursor.moveToFirst()) {
          path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        }
        cursor.close();
      }
      if (newUri != null && sListener!=null) {
        sListener.OnPick(new File(path));
      } else {
        Toast.makeText(this, "没有图片", Toast.LENGTH_SHORT).show();
      }
    }
    finish();
  }

  public interface OnPicPickListener {
    void OnPick(File file);
  }
}
